<template>
  <div class="word-recognition">

    <div class="word-recognition__tips">
      上传的文件中，请您将需要填写的地方使用 <span style="font-weight: bold">${XXX}</span> 的形式填写上，
      文件上传后将会识别出您设定的变量，上传成功后会出现下拉列表，请您根据下拉列表中的选项，为您设定的变量选择合适的关联字段,
      下方有示例文件。
    </div>

    <div v-if="!identifySuccess" class="word-recognition__upload">
      <el-upload
        action="api/v1/upload/file"
        :limit="1"
        accept=".docx"
        :before-upload="beforeUpload"
        :on-success="onSuccess"
        :on-exceed="onExceed"
        :on-remove="onRemove"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" style="margin-top: 10px;">只能上传.docx文件</div>
      </el-upload>
      <el-button type="text" @click="handleDownLoadSampleFile">下载示例文件</el-button>
    </div>

    <div v-if="identifySuccess" style="padding: 20px 0;">
      <el-button @click="handleReupload">重新上传</el-button>
    </div>

    <el-form
      v-if="identifySuccess"
      ref="formRefs"
      label-width="auto"
      label-position="left"
      :rules="rules"
      :model="responseData"
      class="word-recognition__form"
    >
      <el-form-item prop="name" label="合同名称">
        <el-input v-model="responseData.name" placeholder="请输入合同名称" />
      </el-form-item>
      <el-form-item required
        v-for="(item, index) in responseData.fields"
        :key="index"
        :label="item"
      >
        <el-select
          v-model="responseData.value[item]"
          placeholder="请选择"
          filterable
        >
          <el-option
            v-for="items in options"
            :key="items.value"
            :label="items.label"
            :value="items.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <div v-if="identifySuccess" class="word-recognition__button">
      <el-button type="primary" @click="handleComplete">
        {{ type === 'create' ? '完成' : '修改' }}
      </el-button>
    </div>

  </div>
</template>

<script>
import { wordRecognition } from '@/api/agree'
import { getSearchFields } from '@/api/basic'
export default {
  name: '',
  props: {
    type: {
      type: String,
      default: 'create'
    }
  },
  data() {
    return {
      identifySuccess: false,
      responseData: {
        fields: [],
        value: {},
        file: '',
        name: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '合同名称不能为空',
            trigger: ['blur', 'change']
          }
        ]
      },
      options: [],
      fieldSource: ['entry', 'interviews']
    }
  },
  watch: {
    type: {
      handler(n, o) {
        if (this.type === 'edit') {
          this.identifySuccess = true
        }
      },
      immediate: true
    }
  },
  created() {
    this.getTableFields()
  },
  methods: {

    handleEdit(data) {
      this.$nextTick(() => {
        const value = JSON.parse(data.value)
        this.responseData.fields = Object.keys(value)
        this.responseData.name = data.name
        this.responseData.value = value
        this.responseData.file = data.file
        this.responseData.id = data.id
      })
    },

    async getTableFields() {
      const table = JSON.stringify(this.fieldSource)
      try {
        const res = await getSearchFields({ table })
        this.options = this.getFieldsSelectorOptions(res.data)
      } catch (error) {
        this.$message.error(error.message || '获取列表失败')
      }
    },

    getFieldsSelectorOptions(fields) {
      return fields.map(item => ({ value: item.id, label: item.name, field: item.field }))
    },

    async beforeUpload(e) {
      await this.wordRecognitionApi(e)
    },

    async wordRecognitionApi(word) {
      const formData = new FormData()
      formData.append('word', word)
      try {
        const res = await wordRecognition(formData)
        this.responseData.fields = res.data
        this.responseData.value = this.getValue(res.data)
        this.identifySuccess = true
      } catch (error) {
        this.$message.error('识别失败，请重新上传！')
        this.identifySuccess = false
      }
    },

    getValue(data) {
      const obj = {}
      data.forEach(item => {
        obj[item] = null
      })
      return obj
    },

    onSuccess(e) {
      this.responseData.file = e.data.path
      if (e.code === 200 && this.identifySuccess) {
        this.$message.success('文件识别成功')
      }
    },

    onExceed() {
      this.$message.error('超出最大上传数，请移除后继续上传')
    },

    onRemove() {
      this.reset()
    },

    handleReupload() {
      if (this.type === 'create') {
        this.reset()
      } else {
        this.responseData.fields = []
        this.responseData.value = {}
        this.responseData.file = ''
      }
      this.identifySuccess = false
    },
    reset() {
      this.responseData = this.$options.data().responseData
    },

    manualClear() {
      this.reset()
      this.identifySuccess = false
    },

    async handleComplete() {
      this.$refs.formRefs.validate(valid => {
        if (valid) {
          if (this.checkFunc()) {
            this.$emit('complete', this.responseData)
          }
        } else {
          this.$message.error('请将信息填写完整！！！')
        }
      })
    },

    checkFunc() {
      if (!this.responseData.file) {
        this.$message.error('请先上传文件！！！')
        return false
      }
      if (Object.values(this.responseData.value).includes(null)) {
        this.$message.error('请将信息填写完整！！！')
        return false
      }
      return true
    },
    handleDownLoadSampleFile() {
      window.open(
        'https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/test_1688608313_yCwaFMn7hN.docx'
      )
    }
  }

}
</script>

<style scoped lang='scss'>
.word-recognition {
  &__tips {
    padding: 10px;
    border: 1px solid #db2828;
    color: #db2828;
    line-height: 25px;
    background-color: #ffe8e6;
  }
  &__form {
    height: 300px;
    overflow-y: auto;
  }
  &__upload {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  &__button {
    margin-top: 25px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
